//
//  IMB_FileHelper.m
//  BabyNow
//
//  Created by iMobile on 14-4-3.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "IMB_FileHelper.h"

@implementation IMB_FileHelper

// 获取文件的MIME类型
+ (NSString*)mimeType:(NSString *)filePath{
    
    NSString *mimeType;
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    NSURLRequest * request = [NSURLRequest requestWithURL:fileUrl];
    
    NSURLResponse *response;
    NSError *error;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (!error) {
        mimeType = response.MIMEType;
    }
    return mimeType;
}

// 创建目录
+ (BOOL)createDir:(NSString *)dir{
    
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL isDir;
    if ([fm fileExistsAtPath:dir isDirectory:&isDir] && isDir) {
        NSLog(@"%@目录已存在",dir);
        return YES;
    }
    NSError *err;
    BOOL flag = [fm createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:&err];
    if (err) {
        NSLog(@"目录创建失败:%@",[err localizedDescription]);
    }
    return flag;
}

// 将对象归档到指定的文件中
+ (void)archiver:(id)object
          forKey:(NSString *)key
          toFile:(NSString *)filePath{
    
    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:object forKey:key];
    [archiver finishEncoding];
    [data writeToFile:filePath atomically:YES];
}

// 从指定的文件中解档对象
+ (id)unArchiverFromFile:(NSString *)filePath
                 withKey:(NSString *)key{
    NSMutableData *data = [NSMutableData dataWithContentsOfFile:filePath];
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    id obj = [unArchiver decodeObjectForKey:key];
    [unArchiver finishDecoding];
    return obj;
}

@end
